﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using Northwind.NET.Model;

namespace Northwind.NET.EDM.FE.WinForms.Controls
{
    public partial class CustomerOrdersUserControl : BaseUserControl
    {
        public CustomerOrdersUserControl()
        {
            InitializeComponent();
        }

        public override string FormCaption { get { return Settings.Resources.CustomerOrdersFormCaption; } }
        public override dynamic GetEntitySet(ObjectContext context)
        {
            return context.CreateObjectSet<Model.Customer>();
        }

        public override BindingSource UserControlBindingSource { get { return customerBindingSource; }}

        private bool _rowEnterCalled;
        private void orderDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (_rowEnterCalled) return;
            try
            {
                _rowEnterCalled = true;
                const int orderIdCellIndex = 0;
                DataGridViewRow row = orderDataGridView.Rows[e.RowIndex];
                int orderId = (int)row.Cells[orderIdCellIndex].Value;

                setOrderDetailsDataSource(orderId.ToString());
            }
            finally
            {
                _rowEnterCalled = false;
            }
        }

        private void setOrderDetailsDataSource(string orderIdStr)
        {
            int orderId = -1;
            bool ret = Int32.TryParse(orderIdStr, out orderId);
            var result = from o in _context.OrderDetail
                         join p in _context.Product
                         on o.ProductID equals p.ID
                         where o.OrderID == orderId
                         select new
                         {
                             o.ID,
                             o.ProductID,
                             ProductName = p.Name,
                             o.UnitPrice,
                             o.Quantity,
                             o.Discount,
                             ExtendedPrice = (float?)o.UnitPrice * o.Quantity * (1 - o.Discount)
                         };

            customerOrdersProductsDataGridView.DataSource = result;
        }



    }
}
